package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.domain.CourseChapter;
import cn.ztr.ymcc.domain.MediaFile;
import cn.ztr.ymcc.mapper.CourseChapterMapper;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.ICourseChapterService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ztr.ymcc.feign.mediaFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程章节 ， 一个课程，多个章节，一个章节，多个视频 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-02-27
 */
@Service
public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, CourseChapter> implements ICourseChapterService {

    @Autowired
    private mediaFeign mediaFeign;

    /**
     * 根据课程id查找章节
     * @param id
     * @return
     */
    @Override
    public JsonResult listByCourseId(Long id) {
        List<CourseChapter> chapters = baseMapper.selectList(new QueryWrapper<CourseChapter>().eq("course_id", id));
        return JsonResult.me(chapters);
    }

    /**
     * 获取章节播放列表
     * @param id
     * @return
     */
    @Override
    public JsonResult getCourseChapterTree(Long id) {
        //获取章节信息
        List<CourseChapter> chapterList = baseMapper.selectList(new QueryWrapper<CourseChapter>().eq("course_id", id));
        Map<Long,CourseChapter> map = chapterList.stream().collect(Collectors.toMap(CourseChapter::getId,v->v));
        //获取每个章节的课程资料
        JsonResult result = mediaFeign.getMediaFileByCourseId(id);
        List data = (List) result.getData();
       //组装章节
        for (Object mediaFile : data) {
            MediaFile mediaFile1 = JSON.parseObject(JSON.toJSONString(mediaFile), MediaFile.class);
            map.get(mediaFile1.getChapterId()).getMediaFiles().add(mediaFile1);
        }
        return JsonResult.me(chapterList);
    }
}
